<template>
  <div class="order">
    <nav-bar :title="title"></nav-bar>
    <div id="container">
      <el-amap class="amap-box" vid="amapContainer" :events="events"></el-amap>
    </div>
    <div>
      <van-tabbar v-model="active">
        <van-tabbar-item icon="home-o" replace to="/home">首页</van-tabbar-item>
        <van-tabbar-item icon="search" replace to="order">预约</van-tabbar-item>
        <van-tabbar-item icon="friends-o" replace to='/mine'>我的</van-tabbar-item>
      </van-tabbar>
    </div>
  </div>
</template>
<script>
import { lazyAMapApiLoaderInstance } from 'vue-amap'
import NavBar from '@/components/NavBar'
import local from '@/utils/localstorage'
import { getAllCars } from '@/api/car'

export default {
  name: 'Order',
  components: {
    NavBar
  },
  data () {
    return {
      map: null,
      title: '预订',
      active: 1,
      zoom: 18,
      events: {},
      // 储存当前定位
      location: {},
      // 储存汽车定位位置
      position: [],
      // 车辆图标内容
      markerContent: '',
      markers: [],
      // 覆盖物
      circle: null,
      routeLine: null,
      // 距离
      line: 0,
      carId: 0,
      carList: [],
      carNumber: 0,
      walking: null,
      carStatus: 0,
      markersLength: 0
    }
  },
  created () {
    // 获取定位数据
    this.getLngLat()
    // 获取车的经纬度
    this.getCarLngLat()
    this.setMessage()
  },
  mounted () {
    lazyAMapApiLoaderInstance.load().then(() => {
      // eslint-disable-next-line no-undef
      this.map = new AMap.Map('amapContainer', {
        resizeEnable: true,
        center: [this.location.lng, this.location.lat],
        // center: [this.map.getCenter().lng, this.map.getCenter().lat],
        zoom: 17
      })
      console.log(this.map.getCenter().lng)
      // eslint-disable-next-line no-undef
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位，默认:true
        timeout: 10000, // 超过10秒后停止定位，默认：5s
        buttonPosition: 'RB', // 定位按钮的停靠位置
        // eslint-disable-next-line no-undef
        buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
      })
      this.map.addControl(geolocation)
      geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
          // onComplete(result)
          console.log(111)
        } else {
          console.log(222)
        }
      })
    }).then(() => {
      this.setMarker()
      this.setCircle()
    })
  },
  methods: {
    getLngLat () {
      this.location = {
        lng: 101.725767,
        lat: 26.568038
      }
    },
    async getCarLngLat () {
      const { data: res } = await getAllCars({})
      this.carList = res.rows
      this.carList.map((item, index) => {
        // console.log(item)
        this.position.push([parseFloat(item.lngLat.slice(1, 18)), parseFloat(item.lngLat.slice(20, 37))])
      })
      this.markersLength = this.carList.length
      // // 绘制图标
      this.setMarker()
      // 绘制停车区域
      this.setCircle()
    },
    // 设置图标
    setMarker () {
      // console.log('setMarker')
      // eslint-disable-next-line no-undef
      var marker = new AMap.Marker({
        // eslint-disable-next-line no-undef
        position: new AMap.LngLat(this.location.lng, this.location.lat),
        // eslint-disable-next-line no-undef
        // position: new AMap.LngLat(this.map.getCenter().lng, this.map.getCenter().lat),
        icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        // eslint-disable-next-line no-undef
        offset: new AMap.Pixel(-13, -30)
      })
      this.map.add(marker)
      for (var i = 0, marker2; i < this.position.length; i++) {
        // eslint-disable-next-line no-undef
        marker2 = new AMap.Marker({
          map: this.map,
          content: this.markerContent,
          position: this.position[i]
        })
        this.markers.push(marker2)
      }
      this.handleClick()
    },
    addCar () {
      for (var i = 0; i < this.markersLength; i++) {
        this.carList.push(this.carList[i])
      }
    },
    handleClick () {
      for (let n = 0; n < this.markers.length; n++) {
        // 为每个图标添加点击事件
        // eslint-disable-next-line no-undef
        AMap.event.addListener(this.markers[n], 'click', (e) => {
          this.map.clearMap()
          this.setMarker()
          this.setCircle()
          this.handleClick()
          this.addCar()
          // console.log(n, 'n')
          var positionLng = e.lnglat.lng
          var positionLat = e.lnglat.lat
          this.carNumber = n
          this.carId = this.carList[n].id
          this.carStatus = parseInt(this.carList[n].status)
          // console.log(n)
          this.getLine(positionLng, positionLat)
          // 弹出窗口
          this.openWindow(positionLng, positionLat)
          // 绘制路线
          this.createDrving(positionLng, positionLat, this.map)
        })
      }
      local.save('carStatus', this.carStatus)
    },
    // 构建自定义信息窗体
    createInfoWindow (content) {
      // console.log('creat')
      var info = document.createElement('div')
      info.className = 'custom-info input-card content-window-card'

      // 可以通过下面的方式修改自定义窗体的宽高
      info.style.width = '300px'
      info.style.overflow = 'hidden'
      info.style.position = 'fixed'

      // 定义顶部标题
      var top = document.createElement('div')
      var closeX = document.createElement('img')
      top.className = 'info-top'
      closeX.src = 'https://webapi.amap.com/images/close2.gif'
      closeX.onclick = this.closeInfoWindow
      top.style.background = '#fff'
      top.style.borderBottom = '1px solid #ccc'
      top.style.height = '15px'
      closeX.style.float = 'right'
      closeX.style.margin = '4px'
      closeX.style.borderRadius = '3px'
      top.appendChild(closeX)
      info.appendChild(top)

      // 定义中部内容
      var middle = document.createElement('div')
      middle.className = 'info-middle'
      middle.style.backgroundColor = 'white'
      middle.style.width = '300px'
      middle.style.height = '100px'
      middle.style.display = 'flex'
      middle.style.justifyContent = 'space-between'
      middle.innerHTML = content
      info.appendChild(middle)

      // 定义底部内容
      var bottom = document.createElement('div')
      bottom.className = 'info-bottom'
      bottom.style.position = 'relative'
      bottom.style.top = '0px'
      bottom.style.margin = '0 auto'
      var sharp = document.createElement('img')
      sharp.src = 'https://webapi.amap.com/images/sharp.png'
      bottom.appendChild(sharp)
      // info.appendChild(bottom)
      return info
    },
    closeInfoWindow () {
      this.map.clearInfoWindow()
    },
    // 设置图标样式
    setMessage () {
      // 设置图标样式
      this.markerContent = '' +
        '<div class="custom-content-marker">' +
        `   <svg aria-hidden="true" style="width: 50px; height: 30px">
            <use xlink:href="#icon-car"></use>
          </svg>` +
        '</div>'
    },
    // 点击打开弹窗
    openWindow (positionLng, positionLat) {
      // console.log(this.carNumber)
      var content = []
      content.push(`<svg aria-hidden="true" style="width: 80px; height: 80px">
            <use xlink:href="#icon-car"></use>
          </svg>`)
      if (this.carStatus === 1) {
        content.push('<p style="color:red">车辆已被预订</p>')
      }
      if (this.carStatus === 2) {
        content.push('<p style="color:red">车辆已被驾驶</p>')
      }
      content.push('<div><p>距离您' + `${this.line}` + '米</p>' + '<p>可驾驶' + `${this.carList[this.carNumber].estimate}` + '公里</p>' + '<p>起步价' + `${this.carList[this.carNumber].startPrice}` + '元</p>' + '</div>')
      content.push(`<a href='http://localhost:8080/carDetail?carId=${this.carId}&line=${this.line}&carStatus=${this.carStatus}' style="display:block">详细信息</a>`)
      // eslint-disable-next-line no-undef
      var infoWindow = new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: this.createInfoWindow(content.join('<br/>')),
        // eslint-disable-next-line no-undef
        offset: new AMap.Pixel(16, -45)
      })
      infoWindow.open(this.map, [positionLng, positionLat])
    },
    // 设置停车位
    setCircle () {
      // eslint-disable-next-line no-undef
      this.circle = new AMap.Circle({
        center: [this.location.lng, this.location.lat],
        radius: 200, // 半径
        borderWeight: 3,
        strokeColor: '#FF33FF',
        strokeOpacity: 1,
        strokeWeight: 6,
        // eslint-disable-next-line no-dupe-keys
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        strokeStyle: 'dashed',
        strokeDasharray: [10, 10],
        // 线样式还支持 'dashed'
        fillColor: '#1791fc',
        zIndex: 50
      })
      this.circle.setMap(this.map)
    },
    // 绘制路线
    createDrving (positionLng, positionLat, map) {
      var walkingOption = {}
      if (this.walking) {
        this.walking.clear()
        // map.clearMap()
      }
      // eslint-disable-next-line no-undef
      this.walking = new AMap.Walking(walkingOption)
      this.walking.search([this.location.lng, this.location.lat], [positionLng, positionLat], function (status, result) {
        // result即是对应的步行路线数据信息，相关数据结构文档请参考
        if (status === 'complete') {
          if (result.routes && result.routes.length) {
            drawRoute(result.routes[0])
            console.log('绘制步行路线完成')
          }
        } else {
          console.log('步行路线数据查询失败' + result)
        }
      })
      function drawRoute (route) {
        var path = parseRouteToPath(route)
        // eslint-disable-next-line no-undef
        var routeLine = new AMap.Polyline({
          path: path,
          isOutline: true,
          outlineColor: '#ffeeee',
          borderWeight: 2,
          strokeWeight: 5,
          strokeColor: '#0091ff',
          lineJoin: 'round'
        })
        routeLine.setMap(map)
      }
      function parseRouteToPath (route) {
        var path = []
        for (var i = 0, l = route.steps.length; i < l; i++) {
          var step = route.steps[i]
          for (var j = 0, n = step.path.length; j < n; j++) {
            path.push(step.path[j])
          }
        }
        return path
      }
    },
    // 获得距离
    getLine (positionLng, positionLat) {
      // eslint-disable-next-line no-undef
      var m1 = new AMap.Marker({
        draggable: true,
        // eslint-disable-next-line no-undef
        position: new AMap.LngLat(this.location.lng, this.location.lat)
      })
      // eslint-disable-next-line no-undef
      var m2 = new AMap.Marker({
        draggable: true,
        // eslint-disable-next-line no-undef
        position: new AMap.LngLat(positionLng, positionLat)
      })
      var p1 = m1.getPosition()
      var p2 = m2.getPosition()
      this.line = Math.round(p1.distance(p2))
    }
  }
}
</script>

<style scoped lang="scss">
#container {width:100%; height: 100vh; }
</style>
